
from constants import *
import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from tables import *
from utility import *

class Main(webapp.RequestHandler):
    @authorise(USER_NONE)
    def get(self, data):
        if data['user'].loggedIn:
            if data['user'].landlord:
                path = os.path.join(os.path.dirname(__file__), 'templates/landlord_home.html')
            if data['user'].tenant:
                path = os.path.join(os.path.dirname(__file__), 'templates/tenant_home.html')
            if data['user'].admin:
                path = os.path.join(os.path.dirname(__file__), 'templates/admin_home.html')
            self.response.out.write(template.render(path, data))

        else:
            path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
            self.response.out.write(template.render(path, data))

class Logout(webapp.RequestHandler):
    @authorise(USER_NONE)
    def get(self, data):
        data['user'].logout()
        self.redirect("/")

class Login(webapp.RequestHandler):
    @authorise(USER_NONE)
    def get(self, data):#called when login link is clicked
        path = os.path.join(os.path.dirname(__file__), 'templates/login.html')
        self.response.out.write(template.render(path, data))

    def post(self):#called when login form is submitted
        username = self.request.get('username')
        user = User.Validate(username, self.request.get('password'))
        if user:
            MyUser().login(user)
            self.redirect("/add_plot?message=Successfully logged in")
        else:
            self.redirect("/login?message=Login failed, wrong email or password")

class Register(webapp.RequestHandler):
    @authorise(USER_NONE)
    def get(self, data):
        path = os.path.join(os.path.dirname(__file__), 'templates/register.html')
        self.response.out.write(template.render(path, data))

    def post(self):
        password = self.request.get('password')
        if password == self.request.get('password2'):
            user = User.Create(self.request.get('username'), self.request.get('phoneNo'), password, self.request.get('role'))
            if user:
                user.put()
                self.redirect('/login?message=Successfully registered.')
            else:
                self.redirect('/register?message=Phone No or Username already Exists.')
        else:
            self.redirect('/register?message=Passwords don\'t match')

#class LLHome(webapp.RequestHandler):
#    @authorise(USER_LANDLORD)
#    def get(self, data):#called when login link is clicked
#        owner = User.get(data['user'].key)
#        data['plots'] = "Welcome", owner
#        path = os.path.join(os.path.dirname(__file__), 'templates/landlord_home.html')
#        self.response.out.write(template.render(path, data))

class AddPlot(webapp.RequestHandler):
    @authorise(USER_LANDLORD)
    def get(self, data):#called when login link is clicked
        owner = User.get(data['user'].key)
        data['plots'] = Plot.GetPlotsByOwner(owner)
        path = os.path.join(os.path.dirname(__file__), 'templates/add_plot.html')
        self.response.out.write(template.render(path, data))

    @authorise(USER_LANDLORD)
    def post(self, data):
        user = User.get(data['user'].key)
        plot = Plot.Create(self.request.get('plotName'), self.request.get('location'), self.request.get('county'), user)
        plot.put()
        self.redirect('/add_plot?message=Plot Details Saved')

class HouseTypes(webapp.RequestHandler):
    @authorise(USER_LANDLORD)
    def get(self, data):#called when login link is clicked
        data['houseTypes'] = HouseType.GetHouseTypes()
        path = os.path.join(os.path.dirname(__file__), 'templates/add_house_type.html')
        self.response.out.write(template.render(path, data))

    @authorise(USER_LANDLORD)
    def post(self, data):
        houseType = HouseType.Create(self.request.get('houseType'))
        houseType.put()
        self.redirect('/add_house_type?message=Details Saved')

class AddPolicy(webapp.RequestHandler):
    @authorise(USER_LANDLORD)
    def get(self, data):#called when login link is clicked
        plot = Plot.get(self.request.get("plotKey"))
        data['policy'] = Policy.GetPlotPolicy(plot)
        data['houseTypes'] = HouseType.GetHouseTypes()
        data['plot'] = plot
        path = os.path.join(os.path.dirname(__file__), 'templates/policy.html')
        self.response.out.write(template.render(path, data))

    @authorise(USER_LANDLORD)
    def post(self, data):
        plotKey = self.request.get("plotKey")
        houseTypeKey = self.request.get("houseTypeKey")
        plot = Plot.get(plotKey)
        houseType = HouseType.get(houseTypeKey)
        policy = Policy.Create(int(self.request.get('rent')), plot, houseType, self.request.get('penaltyRate'), int(self.request.get('payDeadline')), int(self.request.get('depositRequired')), int(self.request.get('noticeRequired')))
        policy.put()
        self.redirect('/policy?plotKey=' + plotKey + '&message=Details Saved')

class AddHouse(webapp.RequestHandler):
    @authorise(USER_LANDLORD)
    def get(self, data):#called when login link is clicked
        plot = Plot.get(self.request.get("plotKey"))
        data['houses'] = House.GetHousesByPlot(plot)
        data['houseTypes'] = HouseType.GetHouseTypes()
        data['plot'] = plot
        path = os.path.join(os.path.dirname(__file__), 'templates/add_house.html')
        self.response.out.write(template.render(path, data))

    @authorise(USER_LANDLORD)
    def post(self, data):
        try:
            plotKey = self.request.get("plotKey")
            plot = Plot.get(plotKey)
            house = House.Create(self.request.get('houseNo'), self.request.get('houseType'), self.request.get('occupancyStatus'), plot)
            house.put()
            self.redirect('/add_house?plotKey=' + plotKey + '&message=House Details Saved')
        except Exception, e:
            self.response.out.write(str(e))


class OccupancyStatus(webapp.RequestHandler):
    @authorise(USER_LANDLORD)
    def get(self, data):#called when login link is clicked
        plot = Plot.get(self.request.get("plotKey"))
        data['houses'] = House.GetOccupancyStatus(plot)
        data['plot'] = plot
        count = House.NoOfVacantHouse(plot)
        path = os.path.join(os.path.dirname(__file__), 'templates/house_occupancy.html')
        self.response.out.write(template.render(path, data, count))

def main():
    application = webapp.WSGIApplication([('/', Main),
                                         ('/login', Login),
                                         ('/register', Register),
                                         ('/logout', Logout),
                                         #landlord actions
                                         ('/add_plot', AddPlot),
                                         #                                         ('/landlord_home', LLHome),
                                         ('/add_house', AddHouse),
                                         ('/policy', AddPolicy),
                                         ('/house_occupancy', OccupancyStatus),
                                         #by admin
                                         ('/add_house_type', HouseTypes),
                                         ],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
